package com.eascs.tdriskcloud.service.impl;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.eascs.app.runtime.RuntimeSetting;
import com.eascs.tdriskcloud.dao.TDRiskCloudDao;
import com.eascs.tdriskcloud.entity.FraudApiResponse;
import com.eascs.tdriskcloud.entity.HitRule;
import com.eascs.tdriskcloud.entity.Policy;
import com.eascs.tdriskcloud.entity.TdAttribution;
import com.eascs.tdriskcloud.entity.TdHitRule;
import com.eascs.tdriskcloud.entity.TdHitsInformation;
import com.eascs.tdriskcloud.entity.TdOutputApiInfo;
import com.eascs.tdriskcloud.entity.TdOutputField;
import com.eascs.tdriskcloud.entity.TdPersonalDataInfo;
import com.eascs.tdriskcloud.entity.TdPolicySet;
import com.eascs.tdriskcloud.form.Attribution;
import com.eascs.tdriskcloud.form.BaseInfoForm;
import com.eascs.tdriskcloud.form.OutputField;
import com.eascs.tdriskcloud.service.HitInfoParsService;
import com.eascs.tdriskcloud.service.TDRiskCloudService;

import cn.fraudmetrix.riskservice.RuleDetailClient;
import cn.fraudmetrix.riskservice.RuleDetailResult;
import cn.fraudmetrix.riskservice.object.Environment;

@Service
public class TDRiskCloudServiceImpl implements TDRiskCloudService {

	@Inject
	TDRiskCloudDao tdDao;

	@Inject
	HitInfoParsService service;
	
	@Override
	public String querySeqIdById(String Id){
		return tdDao.getSeqIdById(Id);
	}

	@Override
	public String saveOutPutApiInfo(FraudApiResponse apiResp, BaseInfoForm baseInfo) {
		// 入库：个人信息
		TdPersonalDataInfo perSonal = new TdPersonalDataInfo();
		perSonal.setBillCode(baseInfo.getBillCode());
		perSonal.setName(baseInfo.getAccountName());
		perSonal.setIdNumber(baseInfo.getIdNumber());
		perSonal.setAccountMobile(baseInfo.getAccountMobile());
		perSonal.setSeqId(apiResp.getSeq_id());
		perSonal.setCreateTime(new Date(System.currentTimeMillis()));
		tdDao.saveEntity(perSonal);
		String tdId = perSonal.getId();
		// 入库：api输出信息
		TdOutputApiInfo outputApi = new TdOutputApiInfo();
		outputApi.setTdId(perSonal.getId());
		outputApi.setSeqId(apiResp.getSeq_id());
		outputApi.setSuccess(apiResp.getSuccess().toString());
		outputApi.setSpendTime(apiResp.getSpend_time().toString());
		outputApi.setReasonCode(apiResp.getReason_code());
		outputApi.setFinalDecision(apiResp.getFinal_decision());
		outputApi.setFinalScore(apiResp.getFinal_score().toString());
		outputApi.setRiskType(apiResp.getRisk_type());
		outputApi.setPolicySetName(apiResp.getPolicy_set_name());
		outputApi.setCreateTime(new Date(System.currentTimeMillis()));
		tdDao.saveEntity(outputApi);
		// 入库：策略命中的规则
		List<HitRule> hitRule = new ArrayList<>();
		hitRule = apiResp.getHit_rules();
		if (hitRule.size() != 0) {
			for (int i = 0; i < hitRule.size(); i++) {
				TdHitRule hit = new TdHitRule();
				hit.setTdId(perSonal.getId());
				hit.setSeqId(apiResp.getSeq_id());
				hit.setUuid(hitRule.get(i).getUuid());
				hit.setId(hitRule.get(i).getId());
				hit.setName(hitRule.get(i).getName());
				hit.setDecision(hitRule.get(i).getDecision());
				hit.setScore(hitRule.get(i).getScore());
				hit.setCreateTime(new Date(System.currentTimeMillis()));
				tdDao.saveEntity(hit);
			}
		}
		// 入库：决策结果自定义输出
		List<OutputField> outputFiled = new ArrayList<>();
		outputFiled = apiResp.getOutput_fields();
		if (outputFiled.size() != 0) {
			for (int i = 0; i < outputFiled.size(); i++) {
				TdOutputField output = new TdOutputField();
				output.setTdId(perSonal.getId());
				output.setSeqId(apiResp.getSeq_id());
				output.setFieldValue(outputFiled.get(i).getFieldValue());
				output.setValue(outputFiled.get(i).getValue());
				output.setDesc(outputFiled.get(i).getDesc());
				output.setType(outputFiled.get(i).getType());
				output.setCreateTime(new Date(System.currentTimeMillis()));
				tdDao.saveEntity(output);
			}
		}
		// 入库：身份证手机号所属省市
		Attribution attribu = new Attribution();
		attribu = apiResp.getAttribution();
		TdAttribution tdAtt = new TdAttribution();
		tdAtt.setTdId(perSonal.getId());
		tdAtt.setSeqId(apiResp.getSeq_id());
		tdAtt.setIdCardProvince(attribu.getIdCardProvince());
		tdAtt.setIdCardCity(attribu.getIdCardCity());
		tdAtt.setCounty(attribu.getCounty());
		tdAtt.setMobileAddressProvince(attribu.getMobileAddressProvince());
		tdAtt.setMobileAddressCity(attribu.getMobileAddressCity());
		tdAtt.setCreateTime(new Date(System.currentTimeMillis()));
		tdDao.saveEntity(tdAtt);
		// 入库：展示策略集内容
		List<Policy> policySet = new ArrayList<>();
		policySet = apiResp.getPolicy_set();
		if (policySet.size() != 0) {
			for (int i = 0; i < policySet.size(); i++) {
				TdPolicySet policy = new TdPolicySet();
				policy.setTdId(perSonal.getId());
				policy.setSeqId(apiResp.getSeq_id());
				policy.setPolicyUuid(policySet.get(i).getPolicy_uuid());
				policy.setPolicyDecision(policySet.get(i).getPolicy_decision());
				policy.setPolicyMode(policySet.get(i).getPolicy_mode());
				policy.setPolicyScore(policySet.get(i).getPolicy_score());
				policy.setPolicyName(policySet.get(i).getPolicy_name());
				policy.setRiskType(policySet.get(i).getRisk_type());
				policy.setCreateTime(new Date(System.currentTimeMillis()));
				tdDao.saveEntity(policy);
				List<HitRule> rule = new ArrayList();
				rule = policySet.get(i).getHit_rules();
				if (rule.size() != 0) {
					for (int j = 0; j < rule.size(); j++) {
						TdHitRule tdRule = new TdHitRule();
						tdRule.setTdId(policy.getId());
						tdRule.setSeqId(apiResp.getSeq_id());
						tdRule.setUuid(rule.get(j).getUuid());
						tdRule.setId(rule.get(j).getId());
						tdRule.setName(rule.get(j).getName());
						tdRule.setDecision(rule.get(j).getDecision());
						tdRule.setScore(rule.get(j).getScore());
						tdDao.saveEntity(tdRule);
					}
				}
			}
		}
		return tdId;
	}

	@Override
	public void saveHitsInfo(String tdID, String sequenceId) {
		RuntimeSetting runtimeSetting = RuntimeSetting.get();
		// 填写参数
		String partnerCode = "YYTgroup";
		String partnerKey = "ef045843696d417a936de2f4a4e61766";
		String seqId = sequenceId;
		Environment env = null;
		if (runtimeSetting.getEnv().equals("prod")) {
			env = Environment.PRODUCT; // Environment.PRODUCT表示调用生产环境,
										// 测试环境请修改为Environment.SANDBOX
		} else {
			env = Environment.SANDBOX;
		}
		// 调用接口
		RuleDetailClient client = RuleDetailClient.getInstance(partnerCode, env);
		RuleDetailResult result = client.execute(partnerKey, seqId);
		System.out.println(result.getSuccess());
		System.out.println(result.getReasonCode());
		System.out.println(result.getReasonDesc());
		if (result != null) {
			for (int i = 0; i < result.getRules().size(); i++) {
				TdHitsInformation hits = new TdHitsInformation();
				hits.setTdId(tdID);
				hits.setSeqId(sequenceId);
				hits.setConditions(result.getRules().get(i).getConditions().toString());
				if (result.getRules().get(i).getConditions().size() != 0) {
					hits.setType(result.getRules().get(i).getConditions().get(0).getType());
				}
				hits.setDecision(result.getRules().get(i).getDecision());
				hits.setRuleId(result.getRules().get(i).getRuleId());
				hits.setScore(result.getRules().get(i).getScore().toString());
				hits.setCreateTime(new Date(System.currentTimeMillis()));
				tdDao.saveEntity(hits);
			}
		}
	}

	@Override
	public <T> List<T> parsHistData(TdHitsInformation entity) {
		List<T> data = new ArrayList<T>();
		if ("black_list".equals(entity.getType())) {
			data = (List<T>) service.parsHitsBlackList(entity);
		}
		if ("custom_list".equals(entity.getType())) {
			data = (List<T>) service.parsHitsCustomList(entity);
		}
		if ("discredit_count".equals(entity.getType())) {
			data = (List<T>) service.parsHitsDiscreditCount(entity);
		}
		if ("grey_list".equals(entity.getType())) {
			data = (List<T>) service.parsHitsGreyList(entity);
		}
		if ("fuzzy_black_list".equals(entity.getType())) {
			data = (List<T>) service.parsFuzzyBlackList(entity);
		}
		if ("frequency_distinct".equals(entity.getType())) {
			data = (List<T>) service.parsFrequencyDistinct(entity);
		}
		if ("cross_velocity_one_dim".equals(entity.getType())) {
			data = (List<T>) service.parsCrossVelocityOneDim(entity);
		}
		if ("association_partner".equals(entity.getType())) {
			data = (List<T>) service.parsAssociationPartner(entity);
		}
		if ("frequency_one_dim".equals(entity.getType())) {
			data = (List<T>) service.parsFrequencyOneDim(entity);
		}
		if ("frequency_count".equals(entity.getType())) {
			data = (List<T>) service.parsFrequencyCount(entity);
		}
		if ("fp_exception".equals(entity.getType())) {
			data = (List<T>) service.parsFpException(entity);
		}
		if ("geo_ip_distance".equals(entity.getType())) {
			data = (List<T>) service.parsGeoIpDistance(entity);
		}
		if ("proxy_ip".equals(entity.getType())) {
			data = (List<T>) service.parsProxyIp(entity);
		}
		if ("match_address".equals(entity.getType())) {
			data = (List<T>) service.parsMatchAddress(entity);
		}
		if ("gps_distance".equals(entity.getType())) {
			data = (List<T>) service.parsGpsDistance(entity);
		}
		if ("regex".equals(entity.getType())) {
			data = (List<T>) service.parsRegex(entity);
		}
		if ("event_time_diff".equals(entity.getType())) {
			data = (List<T>) service.parsEventTimeDiff(entity);
		}
		if ("time_diff".equals(entity.getType())) {
			data = (List<T>) service.parsTimeDiff(entity);
		}
		if ("active_days_one".equals(entity.getType())) {
			data = (List<T>) service.parsActiveDaysOne(entity);
		}
		if ("active_days_two".equals(entity.getType())) {
			data = (List<T>) service.parsActiveDaysTwo(entity);
		}
		if ("cross_event".equals(entity.getType()) || "cross_velocity_count".equals(entity.getType())) {
			data = (List<T>) service.parsCrossEvent(entity);
		}
		if ("cross_velocity_distinct".equals(entity.getType())) {
			data = (List<T>) service.parsCrossVelocityDistinct(entity);
		}
		if ("calculate".equals(entity.getType()) || "min_max".equals(entity.getType())) {
			data = (List<T>) service.parsCalculate(entity);
		}
		if ("last_match".equals(entity.getType())) {
			data = (List<T>) service.parsLastMatch(entity);
		}
		if ("count".equals(entity.getType())) {
			data = (List<T>) service.parsCount(entity);
		}
		if ("association_industry".equals(entity.getType())) {
			data = (List<T>) service.parsAssociationIndustry(entity);
		}
		if ("cross_partner".equals(entity.getType())) {
			data = (List<T>) service.parsCrossPartner(entity);
		}
		if ("four_calculation".equals(entity.getType()) || "function_kit".equals(entity.getType())) {
			data = (List<T>) service.parsFourCalculation(entity);
		}
		if ("usual_browser".equals(entity.getType()) || "usual_device".equals(entity.getType())
				|| "usual_location".equals(entity.getType())) {
			data = (List<T>) service.parsUsualBrowser(entity);
		}
		if ("keyword".equals(entity.getType())) {
			data = (List<T>) service.parsKeyword(entity);
		}
		if ("android_cheat_app".equals(entity.getType())) {
			data = (List<T>) service.parsAndroidCheatApp(entity);
		}
		if ("ios_cheat_app".equals(entity.getType())) {
			data = (List<T>) service.parsIosCheatApp(entity);
		}
		if ("android_emulator".equals(entity.getType())) {
			data = (List<T>) service.parsAndroidEmulator(entity);
		}
		if ("device_status_abnormal".equals(entity.getType())) {
			data = (List<T>) service.parsDeviceStatusAbnormal(entity);
		}
		if ("suspected_team".equals(entity.getType())) {
			data = (List<T>) service.parsSuspectedTeam(entity);
		}
		return data;
	}

}
